﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
////////////////
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;

namespace LearnCSharp
{
	class Compilateur
	{
		public static void Test()
		{
			string sc = @"
				using System;
				class ClasseProg
				{
					public double f(int a, int b)
					{
						return a+b;
					}
				}
			";

			////////////////////
			// DECLARATION DU COMPILATEUR
			CompilerParameters cp = new CompilerParameters();
			cp.GenerateInMemory = true;

			// Ancienne magnère
			/*
			CSharpCodeProvider cscp = new CSharpCodeProvider();
			ICodeCompiler icc		= cscp.CreateCompiler();
			cr = icc.CompileAssemblyFromSource(cp, sc);
			 * */

			// Nouvelle manière
			CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
			CompilerResults cr = provider.CompileAssemblyFromSource(cp, sc);

			////////////////////
			// ERRORS COMPILATION
			if( cr.Errors.Count > 0 )
			{				
				for(int i=0; i<cr.Errors.Count; i++)
				{
					Console.WriteLine("Error compil : line {0} : {1}", cr.Errors[i].Line, cr.Errors[i].ErrorText);
				} 
			}
			else
			{
				////////////////////
				// ERRORS COMPILATION
				object o = cr.CompiledAssembly.CreateInstance("ClasseProg");
				Type t = o.GetType();
				int a = 12;
				int b = 18;
				object[] to = {a,b};
				double somme = (double) t.InvokeMember("f", BindingFlags.InvokeMethod, null, o, to);

				Console.WriteLine("Résultat executionf de la compil : {0}", somme.ToString());
			}
						
		}
	}
}
